begin tran


declare @TreeViewLinkTree table
(
	TreeViewID int,
	RootTreeID int
)

insert into @TreeViewLinkTree
select TreeViewID,RootTreeID from TreeView

update TreeView set RootTreeID = NULL

declare @OldTaskTree Table
(
	[NewTreeID] int IDENTITY(1,1),
--	[NewPTreeID] int ,
--	[NewLinkTreeID] int,

	[TreeID] [int] Primary key,
	[PTreeID] [int],
	[LinkTreeID] [int],
	[LinkTaskID] [int],
	[TreeTitle] [varchar] (256),
	[TreeVersion] [int],
	[TreeType] [int],
	[DeleteState] [int],
	[TreeLastModifyTime] [datetime],
	[TreeLastModifyUser] [varchar] (256),
	[TreeIndex] [bigint]
)

insert into @OldTaskTree
(	[TreeID],
	[PTreeID],
	[LinkTreeID],
	[LinkTaskID],
	[TreeTitle],
	[TreeVersion],
	[TreeType],
	[DeleteState],
	[TreeLastModifyTime],
	[TreeLastModifyUser],
	[TreeIndex]
)
select TaskTree.* from 
TaskTree order by TreeID


delete from TaskTree
SET IDENTITY_INSERT TaskTree ON

insert into TaskTree
(
[TreeID],
[PTreeID],
[LinkTreeID],
[LinkTaskID],
[TreeTitle],
[TreeVersion],
[TreeType],
[DeleteState],
[TreeLastModifyTime],
[TreeLastModifyUser],
[TreeIndex]
)
select 
T1.NewTreeID as TreeID,
T2.NewTreeID as PTreeID,
T3.NewTreeID as LinkTreeID,
T1.[LinkTaskID],
T1.[TreeTitle],
T1.[TreeVersion],
T1.[TreeType],
T1.[DeleteState],
T1.[TreeLastModifyTime],
T1.[TreeLastModifyUser],
T1.[TreeIndex]
from @OldTaskTree as T1
left join @OldTaskTree as T2
on T1.PTreeID=T2.TreeID
left join @OldTaskTree as T3
on T1.LinkTreeID=T3.TreeID

DBCC CHECKIDENT ('TaskTree',RESEED,1)
DBCC CHECKIDENT ('TaskTree',RESEED)

SET IDENTITY_INSERT TaskTree OFF

--select TreeViewID,RootTreeID from TreeView

select * from @TreeViewLinkTree

update TreeView set
RootTreeID=V.TreeID
from 
(
select TV.TreeViewID as ViewID,T.NewTreeID as TreeID
from @TreeViewLinkTree as TV
join @OldTaskTree as T
on TV.RootTreeID=T.TreeID
and TV.TreeViewID=TreeViewID
) as V

where V.ViewID=TreeViewID


exec spm_GetFullTree 1,''

--commit
rollback